package com.dorsica.dbupdate;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.util.GroovyScriptEngine;
import groovy.util.ScriptException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.h2.tools.RunScript;

public class ExecMojo extends DbUpdateAbstractMojo {

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        // TODO Auto-generated method stub

    }

    protected void controleScriptFile(String scriptFile)
            throws FileNotFoundException {
        if (rootUpdateDir == null || !new File(rootUpdateDir).exists()) {
            throw new FileNotFoundException("Folder " + rootUpdateDir
                    + " not found");
        }

        if (!new File(rootUpdateDir, scriptFile).exists()) {
            throw new FileNotFoundException("File " + scriptFile
                    + " not found in folder " + rootUpdateDir);
        }
    }

    protected void execGroovy(String groovyFile) throws ScriptException,
            IOException {
        controleScriptFile(groovyFile);

        GroovyScriptEngine gse;
        try {
            gse = new GroovyScriptEngine(rootUpdateDir);
        } catch (IOException e) {
            throw new IOException("Can't access folder " + rootUpdateDir, e);
        }

        Binding binding = new Binding();

        Binding sqlObjectBinding = new Binding();
        sqlObjectBinding.setVariable("url", url);
        sqlObjectBinding.setVariable("user", user);
        sqlObjectBinding.setVariable("password", password);
        sqlObjectBinding.setVariable("driver", driver);
        GroovyShell shell = new GroovyShell(sqlObjectBinding);

        Object value = shell
                .evaluate("import groovy.sql.Sql; Sql.newInstance( url, user, password, driver )");

        binding.setVariable("sql", value);

        try {
            gse.run(groovyFile, binding);
        } catch (Exception e) {
            throw new ScriptException("Script " + groovyFile
                    + " can't be executed", e);
        }
    }

    protected void execSql(String sqlFile) throws SQLException {

        new RunScript().runTool("-url", url, "-driver", driver, "-user", user,
                "-password", password, "-script", new File(rootUpdateDir,
                        sqlFile).getAbsolutePath());

    }
}
